package com.plasticcode.performance;

import java.util.HashMap;
import java.util.Map;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

import org.junit.Test;

import com.plasticcode.log.domain.Run;
import com.plasticcode.log.domain.Runner;

/**
 * Compares EhCache's performance vs a HashMap.
 */
public class CachingTestCase {
    private static int SAMPLES = 50000; 
        
    private long nextId = 100000;
    
    @Test public void testHashMapCache() throws Exception {
        PerformanceController controller = new PerformanceController(
                "Hashmap lookup peformance", new MeasuredOperation() {
            Map<Long, Runner> runnerMap = new HashMap<Long, Runner>();
            long id;
            
            public void setup(int children) {
                for (int i = 0; i < children; i++) {
                    Runner runner = TestDataHelper.createRunnerWithChildren(5);
                    id = nextId++;
                    runnerMap.put(id, runner);
                }
            }

            public void run(int children, int samples) {
                for(int i = 0; i < samples; i++) {
                    Runner runner = runnerMap.get(id);
                    runner.getName();
                    for (Run run : runner.getRuns()) { }                     
                }
            }
        });
        controller.measure(SAMPLES);
    }
    

    @Test public void testEhCache() throws Exception {
        PerformanceController controller = new PerformanceController(
                "EhCache lookup performance", new MeasuredOperation() {
            Cache cache;
            long id;
            
            public void setup(int children) {
                CacheManager cacheManager = new CacheManager();
                cache = cacheManager.getCache("com.plastic.log.domain.Runner");
                for (int i = 0; i < children; i++) {
                    Runner runner = TestDataHelper.createRunnerWithChildren(5);
                    id = nextId++;
                    cache.put(new Element(id, runner));
                }
            }

            public void run(int children, int samples) {
                for(int i = 0; i < samples; i++) {
                    Runner runner = (Runner) cache.get(id).getValue();
                    runner.getName();
                    for (Run run : runner.getRuns()) { }                     
                }
            }
        });
        controller.measure(SAMPLES);        
    }
}
